// pages/login/index.js
import userService from '../../api/UserService.js';
import appService from '../../api/AppService.js';
import tokenManager from '../../mpf/auth/token-manager.js';
import storage from '../../mpf/cache/storage.js';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    token:null,
    // 授权状态
    userInfoType:true,
    phone:'',
    captcha: '',
    ticket:'',
    captchaLocked:false,
    submitLocked:false,
    captchaText: '获取验证码',
    countDown: 60,
    redirectTo:'',
    titleTxt:'绑定手机',
    popType: false,
    codeImg:'',
    code: null,
    imgNum: 0,
    wxKey:'',
    wxCode: null,
    phonePopType: false
  },
  onLoad: function (options){
    // 初始化获取code
    this.getWxCode();
    // 获取当前跳转的路由
    this.getWxCode()
    var redirectTo = options.redirect || 'pages/index/index';
    this.setData({
      redirectTo: decodeURIComponent(redirectTo)
    });
  },
  onShow: function () {
  },
  showPop: function(e){
    this.setData({
      popType: !this.data.popType
    })
  },
  showPhonePop: function(){
    this.setData({
      phonePopType: !this.data.phonePopType
    })
  },
  // 不同意
  noAgreement: function(){
    this.setData({
      userInfoType: false
    })
  },
  // 获取微信code
  getWxCode:function(){
    wx.login({
      success: (response) => {
        this.setData({
          wxCode: response.code ? response.code:null
        })
      }
    })
  },
  // 输入验证码
  codeInput:function(e){
    this.setData({
      code: e.detail.value
    })
  },
  // 确认验证码
  isImgCode:function(){
    if (this.data.code == null || this.data.code == '' || this.data.code.length != 5){
      global.showError('请输入验证码')
      return
    }
    this.getCaptcha()
  },
  // 切换图片
  changeImg: function(){
    var num = this.data.imgNum+1;
    var url = global.API_BASE_PATH + '/rest/view/captcha/getCaptcha?mobile=' + this.data.phone+'&num=' + num
    this.setData({
      imgNum: num,
      codeImg: url 
    })
  },
  showLoading: function(){
    global.showLoading('授权登录');
  },
  // 微信登录
  getUserInfo: function (e){
    // 获取微信code
    this.getWxCode();
    if (e.detail.userInfo) {
      if(this.data.wxCode){
        var data = {
          "type":2,
          "source":'xcxtg',
          "encryptedData": e.detail.encryptedData,
          "iv": e.detail.iv,
          "code": this.data.wxCode
        };
        // 邀请助力id
        if (storage.get('inviteId') != '') {
          data.pages = 'tgvip' + storage.get('inviteId')
        }
        // 去准备授权判断用户是否存在
        this.wxLogin(data);
      }
    } else{
      global.hideLoading();
    }
  },
  wxLogin: function (loginData) {
    // 重新更新code
    this.getWxCode()
    // 验证授权登录
    userService.wxLogin({
      query: loginData,
      success: (response)=>{
        if (response.data&&response.data.ifBind){
          this.loginSuccess(response.data)
        }
        else{
          this.setData({
            wxKey: loginData.code,
            phonePopType: true
            // userInfoType: false
          })
          global.hideLoading();
        }
      },
      complete:() =>{}
    });
  },
  // 获取手机号
  getPhone: function(e){
    global.showLoading('登录中');
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      var data = {
        "encryptedData": e.detail.encryptedData,
        "source":'xcxtg',
        "iv": e.detail.iv,
        "code": this.data.wxCode,
        "wxKey": this.data.wxKey
      };
      // 邀请助力id
      if (storage.get('inviteId')!='') {
        data.pages = 'tgvip' + storage.get('inviteId')
      }
      // 请求手机号接口登录
      userService.getPhoneLogin({
        query: data,
        success: (response) => {
          this.loginSuccess(response.data)
        },
        complete: (res) => {
          if (res.data.respCode == -1) {
            global.showError(res.data.message);
            // 获取微信code
            this.getWxCode();
          }
          this.setData({
            submitLocked: false
          })
        }
      })
    } else {
      global.hideLoading();
    }
  },
  /**
   * 手机号码输入
   */
  phoneInput: function (e) {
    this.setData({
      phone: e.detail.value
    })
  },
  /**
   * 验证码输入
   */
  captchaInput: function (e) {
    this.setData({
      captcha: e.detail.value
    })
  },
  /**
   * 获取验证码
   */
  getCaptcha: function() {
    if (this.data.captchaLocked) {
      return
    }
    if (!this.checkPhone()) {
      global.showError('请输入正确的手机号码')
      return;
    }
    global.showLoading('发送中')
    this.setData({
      captchaLocked: true
    })
    var that = this
    userService.getCaptcha({
      query:{
        mobile: this.data.phone,
        imgCode: this.data.code
      },
      success: (response) =>{
        var countStart = new Date().getTime();
        that.captchaText = this.data.countDown;
        var t = setInterval(() => {
          var time = this.data.countDown - Math.floor((new Date().getTime() - countStart) / 1000)
          if (time < 0) {
            this.setData({
              captchaText: '重新获取',
              captchaLocked: false
            })
            clearInterval(t)
          } else {
            this.setData({
              captchaText: time + 's后重新获取',
              popType: false
            })
          }
        }, 1000)
      },
      error: () => {
        this.setData({
          captchaLocked: false
        })
      },
      complete: (res) => {
        global.hideLoading();
        if (res.data&&res.data.respCode == 2) {
          this.setData({
            captchaLocked: false
          })
          this.changeImg()
          this.setData({
            popType: true
          })
        } else {
          this.setData({
            popType: false
          })
        }
      }
    })
  },
  /**
   * 短信验证码绑定
   */
  doBind: function() {
    if (this.data.captcha.length != 4 || this.data.phone.length != 11){
      return
    }
    if (this.data.submitLocked) {
      return
    }
    if (!this.checkPhone()) {
      global.showError('请输入正确的手机号码')
      return
    }
    if (!this.data.captcha) {
      global.showError('请输入验证码')
      return
    }
    this.setData({
      submitLocked:true
    })
    global.showLoading('登录中');
    var data = {
      mobile: this.data.phone,
      captcha: this.data.captcha,
      wxKey: this.data.wxKey
    }
    // 邀请助力id
    if (storage.get('inviteId') != '') {
      data.pages = 'tgvip' + storage.get('inviteId')
    }
    userService.phoneLogin({
      query: data,
      success:  (response) => {
        this.loginSuccess(response.data)
      },
      complete:  (res) => {
        if(res.data.respCode == -1) {
          global.showError(res.data.message);
        }
        this.setData({
          submitLocked: false
        })
      }
    })
  },
  checkPhone: function() {
    return this.data.phone !== '' && /^1[3,4,5,7,8,9]\d{9}$/.test(this.data.phone)
  },
  goLink: function (e) {
    var link = e.currentTarget.dataset.link;
    global.webview(link);
  },
  loginSuccess: function(oauthAccessToken){
    storage.set('wechatOpenId', oauthAccessToken.xcxPayOpenId);
    // 初始化数据存储
    tokenManager.set(oauthAccessToken.token);
    appService.init();
    global.successToast('登录成功');
    storage.set('webLogin', 1)
    storage.set('isOperate', 1);
    setTimeout(()=>{
      wx.navigateBack({
        delta: 1
      })
    },300)
    this.setData({
      token: encodeURIComponent(JSON.stringify(oauthAccessToken.token))
    });
  }
})